<template>
  <div class="upload-container">
    <el-button
      icon="el-icon-upload"
      size="mini"
      type="primary"
      @click=" dialogVisible=true"
      style="margin-top: 5px;margin-right: 5px"
      plain
      round
    >上传图片</el-button>
    <el-dialog
      :visible.sync="dialogVisible"
      :modal-append-to-body="true"
      append-to-body
      v-drag-zoom
      title="图片上传"
    >
      <el-upload
        ref="upload"
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
        :on-progress="handleFileUploadProgress"
        :before-upload="beforeUpload"
        :class="dvUploadStatus ? 'editor-slide-upload' : 'editor-slide-upload editor-disable-upload'"
        :action="upload.url + '?path=' + upload.path"
        :headers="headers"
        list-type="picture-card"
        drag
      >
        <el-button slot="trigger" :disabled="!dvUploadStatus" size="small" type="primary">点击上传</el-button>
        <div class="el-upload__text" v-if="!dvUploadStatus">
          如需上传文件，请从文件管理上传！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSelectFile">从文件管理选择</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-dialog>
    <!-- 文件管理  -->
    <file-select :visible.sync="showFileSelect" v-if="showFileSelect" :file-ext-name="fileType" :dv-multi-file="true" @setFileUrl="setImageUrl"/>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    }
  },
  data() {
    return {
      dialogVisible: false,
      listObj: {},
      fileList: [],
      // 上传文件路径
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的文件夹
        path: '/blog/blog-content-img',
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/file/file/upload"
      },
      headers: {
        // 上传文件的请求头
        Authorization: "Bearer " + getToken()
      },
      // 显示文件管理
      showFileSelect: false,
      // 文件类型
      fileType: ["png", "jpg", "jpeg", 'blob'],
      // 是否启用文件上传
      dvUploadStatus: false
    }
  },
  methods: {
    checkAllSuccess() {
      return Object.keys(this.listObj).every(
        (item) => this.listObj[item].hasSuccess
      )
    },
    handleSubmit() {
      const arr = Object.keys(this.listObj).map((v) => this.listObj[v])
      if (!this.checkAllSuccess()) {
        this.$message(
          '请等待所有图片成功上传，如果存在网络问题，请重新打开页面并重新上传!'
        )
        return
      }
      this.$emit('successCBK', arr)
      this.listObj = {}
      this.fileList = []
      this.dialogVisible = false
    },
    handleSuccess(response, file) {
      this.$message.success(response.msg)
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          this.listObj[objKeyArr[i]].url = response.data.url
          this.listObj[objKeyArr[i]].hasSuccess = true
          this.fileList.push(this.listObj[objKeyArr[i]])
          return
        }
      }
    },
    handleRemove(file) {
      const uid = file.uid
      const objKeyArr = Object.keys(this.listObj)
      for (let i = 0, len = objKeyArr.length; i < len; i++) {
        if (this.listObj[objKeyArr[i]].uid === uid) {
          delete this.listObj[objKeyArr[i]]
          return
        }
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    beforeUpload(file) {
      // 图片上传前的校验
      const isJPEG = file.name.split('.')[1] === 'jpeg'
      const isJPG = file.name.split('.')[1] === 'jpg'
      const isPNG = file.name.split('.')[1] === 'png'
      const isBMP = file.name.split('.')[1] === 'bmp'
      const isGIF = file.name.split('.')[1] === 'gif'
      const isLt2000K = file.size / 1024 / 500 < 4
      if (!isJPG && !isJPEG && !isPNG && !isBMP && !isGIF) {
        this.$message.error('上传图片只能是 JPEG/JPG/PNG/BMP/GIF 格式!')
        return false
      }
      if (!isLt2000K) {
        this.$message.error('单张图片大小不能超过 2000KB!')
        return false
      }
      if ((isJPEG || isJPG || isPNG || isBMP || isGIF) && isLt2000K) {
        const _self = this
        const _URL = window.URL || window.webkitURL
        const fileName = file.uid
        this.listObj[fileName] = {}
        return new Promise((resolve, reject) => {
          const img = new Image()
          img.src = _URL.createObjectURL(file)
          img.onload = function() {
            _self.listObj[fileName] = {
              hasSuccess: false,
              uid: file.uid,
              width: this.width,
              height: this.height
            }
          }
          resolve(true)
        })
      }
    },
    setImageUrl(urlArr) {
      this.showFileSelect = false
      for (const url of urlArr) {
        const checkExist = this.fileList?.filter(item => item.url === url);
        if (checkExist.length === 0) {
          const uid = new Date().getTime() + Math.round(Math.random() * 100);
          const obj = {
            uid: uid,
            url: url,
            hasSuccess: true,
            name: ''
          }
          this.$set(this.listObj, uid, obj)
          this.fileList.push(obj)
        }
      }
    },
    handleSelectFile() {
      this.showFileSelect = true
    }
  }
}
</script>

<style lang="scss" scoped>
.editor-slide-upload {
  ::v-deep .el-upload--picture-card {
    width: 100%;
  }
  ::v-deep .el-upload-dragger {
    width: 100%;
    height: 100%;
  }
}
.editor-disable-upload {
  ::v-deep .el-upload--picture-card {
    pointer-events: none;
    cursor: not-allowed;
  }
}
.el-dialog__wrapper {
  z-index: 10000 !important;
}
</style>
